package com.sgb.kjwl.view.ui.fragment.packers;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtPackerEngineeringCompanyBinding;
import com.sgb.kjwl.model.entity.packers.EngineeringCompanyEntity;
import com.sgb.kjwl.model.entity.packers.PickResultEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.adapter.packers.EngineeringCompanyAdapter;
import com.sgb.kjwl.view.widget.PickPopWindow1;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.packers.TwoLevelPopLinkWindow;
import com.sgb.kjwl.viewmodel.packers.PackersEngineeringCompanyModel;
import com.swgk.core.base.model.entity.SelectPopEntity;
import com.swgk.core.customview.ScreenChildTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * @author : younghow
 * @date : 2021/12/3 11:29
 * description:工程公司
 */
public class BuilderCompanyFragment extends AppLazyFragment {

    public PackersEngineeringCompanyModel viewModel;
    private AtPackerEngineeringCompanyBinding binding;
    private EngineeringCompanyAdapter adapter;

    /**
     * 团队规模
     */
    private PickPopWindow1 popTeamSize;
    private PickResultEntity pickResultTeamSize;
    /**
     * 所在区域
     */
    private ThreeLevelAreaWindow popCity;
    private PickResultEntity pickResultProvince;
    private PickResultEntity pickResultCity;
    private PickResultEntity pickResultArea;
    private AddressEntity mAddress;
    private TwoLevelPopLinkWindow<AddressEntity> mTwoLevelPopWindow;
    private String mQualificationTypeNo;
    private String mQualificationClassNo;
    private String mQualificationClassName;
    private String mAreaCode,mAreaName;
    private boolean isLoadMore;
    private List<AddressEntity<List<AddressEntity>>> workTypeList;

    public static BuilderCompanyFragment newInstance() {
        BuilderCompanyFragment intent = new BuilderCompanyFragment();
        Bundle bundle = new Bundle();
        intent.setArguments(bundle);
        return intent;
    }

    private void initFilterData(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
        viewModel.getNewList("", "", "", "全部".equals(pickResultTeamSize.getName()) ? "" : pickResultTeamSize.getName(),
                pickResultProvince.getNo(), pickResultCity.getNo(), pickResultArea.getNo(), isLoadMore, mQualificationTypeNo, mQualificationClassNo);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.at_packer_engineering_company,container,false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {

        binding.setLifecycleOwner(this);
        viewModel = new ViewModelProvider(this).get(PackersEngineeringCompanyModel.class);

        setTextButton();

        binding.sct.onSetCallPop(new ScreenChildTextView.ICallPop() {
            @Override
            public void openPop(int position, TextView content, LinearLayout bg, SelectPopEntity entity) {
                if (position == 0) {
                    showTeamSizePopWindow();
                } else if (position == 1) {
                    showCityPop();
                }
            }
        });
        

        if (adapter == null) {
            adapter = new EngineeringCompanyAdapter(getActivity(), null, Glide.with(this));
        }

        adapter.setOnItemClick(new AdapterOnItemClick<EngineeringCompanyEntity>() {
            @Override
            public void onItemClick(EngineeringCompanyEntity entity, int position) {
                if (TextUtils.isEmpty(entity.getId())) {
                    ToastUtil.show(getActivity(), "企业店铺id不能为空");
                    return;
                }
                WebsiteInfoActivity.start(getActivity(), entity.getCompanyNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0,
                0,
                0,
                getResources().getDimension(R.dimen.dp5)));
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData(false);
            }

            @Override
            public void onLoadMore() {
                initFilterData(true);
            }
        });

        mAreaCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE,"");
        mAreaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME,"");

        pickResultTeamSize = new PickResultEntity();
        pickResultProvince = new PickResultEntity();
        pickResultCity = new PickResultEntity();
        pickResultArea = new PickResultEntity();

        mAddress = (AddressEntity) getArguments().getSerializable("entity");

        binding.rvPackerChangeFirstContentTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mQualificationTypeNo = workTypeList.get(tab.getPosition()).getNo();

                if (tab.getPosition() == 0){
                    binding.rvPackerChangeFirstContentTwoLevel.setVisibility(View.GONE);
                }else {
                    binding.rvPackerChangeFirstContentTwoLevel.setVisibility(View.VISIBLE);
                }

                if (workTypeList.get(tab.getPosition()).getChildren() != null && workTypeList.get(tab.getPosition()).getChildren().size() > 0){
                    binding.rvPackerChangeFirstContentTwoLevel.removeAllTabs();
                    for (AddressEntity child : workTypeList.get(tab.getPosition()).getChildren()) {
                        binding.rvPackerChangeFirstContentTwoLevel.addTab(binding.rvPackerChangeFirstContentTwoLevel.newTab().setText(child.getName()));
                    }
                }else {
                    binding.rvPackerChangeFirstContentTwoLevel.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        binding.rvPackerChangeFirstContentTwoLevel.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mQualificationClassNo = workTypeList.get(binding.rvPackerChangeFirstContentTitle.getSelectedTabPosition()).getChildren().get(tab.getPosition()).getNo();
                mQualificationClassName = workTypeList.get(binding.rvPackerChangeFirstContentTitle.getSelectedTabPosition()).getChildren().get(tab.getPosition()).getName();
                initFilterData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        initLiveData();
    }

    private void initLiveData() {
        viewModel.companyList.observe(getViewLifecycleOwner(), engineeringCompanyEntities -> {
            if (isLoadMore) {
                if (engineeringCompanyEntities != null && engineeringCompanyEntities.size() > 0) {
                    adapter.addDatas(engineeringCompanyEntities);
                }
                binding.recyclerView.setNoMore(engineeringCompanyEntities == null || engineeringCompanyEntities.size() < 10);
            } else {
                binding.recyclerView.refreshComplete();
                if (engineeringCompanyEntities != null && engineeringCompanyEntities.size() > 0) {
                    binding.emptyView.setVisibility(View.GONE);
                    adapter.setDatas(engineeringCompanyEntities);
                    binding.recyclerView.smoothScrollToPosition(0);
                } else {
                    adapter.clearDatas();
                    binding.emptyView.setVisibility(View.VISIBLE);
                }
            }
        });

        viewModel.loading.observe(getViewLifecycleOwner(), aBoolean -> DialogHelper.showProgressDialog(getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));

        viewModel.popList.observe(getViewLifecycleOwner(), pickSelectEntities -> {
            if (popTeamSize == null) {
                popTeamSize = new PickPopWindow1(getContext());
                popTeamSize.setBgView(binding.grayLayout);
                popTeamSize.setOnResultClick((PickPopWindow1.OnResultClick) (key1, key2, key3) -> {
                    pickResultTeamSize.setNo((String) key1);
                    pickResultTeamSize.setName((String) key2);
                    pickResultTeamSize.setPosition((int) key3);
                    if (TextUtils.isEmpty((String) key2) || TextUtils.equals("全部", (String) key2)) {
                        binding.sct.contentSelect("团队规模",false,false,0);
                    } else {
                        binding.sct.contentSelect((String) key2,true,false,0);
                    }
                    initFilterData(false);
                });
                popTeamSize.setOnDismissListener(() -> binding.sct.contentSelect(!"团队规模".equals(binding.sct.getName(0)),false,0));

                popTeamSize.setData(pickSelectEntities);
            }
        });

        viewModel.cityList.observe(getViewLifecycleOwner(), new Observer<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
            @Override
            public void onChanged(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntities) {
                if (popCity == null) {
                    popCity = new ThreeLevelAreaWindow(getActivity()) {
                        @Override
                        protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.provinceClick(baseAreaEntity, position);
                            pickResultProvince.setNo(baseAreaEntity.getNo());
                            pickResultProvince.setName(baseAreaEntity.getSimpleName());
                            if ("全部".equals(baseAreaEntity.getSimpleName()) || pickResultProvince.getName().equals(baseAreaEntity.getSimpleName())) {
                                pickResultCity.setNo("");
                                pickResultCity.setName("");
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.cityClick(baseAreaEntity, position);
                            pickResultCity.setNo(baseAreaEntity.getNo());
                            pickResultCity.setName(baseAreaEntity.getSimpleName());
                            if ("全部".equals(baseAreaEntity.getSimpleName()) || pickResultCity.getName().equals(baseAreaEntity.getSimpleName())) {
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.areaClick(baseAreaEntity, position);
                            pickResultArea.setNo(baseAreaEntity.getNo());
                            pickResultArea.setName(baseAreaEntity.getSimpleName());
                        }

                        @Override
                        protected void reset() {
                            super.reset();
                            pickResultProvince.clear();
                            pickResultCity.clear();
                            pickResultArea.clear();
                            binding.sct.contentSelect("全部",true,false,1);
                            popCity.dismiss();
                            initFilterData(false);
                        }
                    };
                    popCity.setBgView(binding.grayLayout);
                    popCity.setProvinceSingle();
                    popCity.setCitySingle();
                    popCity.setAreaSingle();
                    popCity.setShowSimpleName(true);
                    pickResultProvince.setName(mAreaName);
                    popCity.setOnResultClick((key1, key2, key3) -> {
                        initFilterData(false);
                        if (!"全部".equals(pickResultArea.getName()) && !"".equals(pickResultArea.getName())) {
                            binding.sct.contentSelect(pickResultArea.getName(),true,false,1);
                            return;
                        } else {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,1);
                        }

                        if (!"全部".equals(pickResultCity.getName()) && !"".equals(pickResultCity.getName())) {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,1);
                            return;
                        } else {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,1);
                        }

                        if (!"全部".equals(pickResultProvince.getName()) && !"".equals(pickResultProvince.getName())) {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,1);
                        } else {
                            binding.sct.contentSelect("全部",true,false,1);
                        }
                    });
                    popCity.setOnDismissListener(() -> binding.sct.contentSelect(!"地区".equals(binding.sct.getName(1)),false,1));

                    popCity.setDataForAll(addressEntities, true, mAreaCode);
                }
            }
        });

        viewModel.dataList.observe(getViewLifecycleOwner(), new Observer<List<AddressEntity<List<AddressEntity>>>>() {
            @Override
            public void onChanged(List<AddressEntity<List<AddressEntity>>> addressEntities) {
                workTypeList = addressEntities;
                for (AddressEntity<List<AddressEntity>> addressEntity : addressEntities) {
                    binding.rvPackerChangeFirstContentTitle.addTab(binding.rvPackerChangeFirstContentTitle.newTab().setText(addressEntity.getName()));
                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        pickResultProvince.setNo(mAreaCode);
        binding.sct.contentSelect(mAreaName,true,false,1);
        viewModel.getIntelligenceType();
        initFilterData(false);
        viewModel.getCityList();
        viewModel.getTeamSize(0);
    }

    /**
     * 团队规模pop
     *
     * @param
     */
    public void showTeamSizePopWindow() {
        binding.sct.contentSelect(false,true,0);
        popTeamSize.showPopwindow0(binding.sct);
    }

    /**
     * 省市区pop
     *
     * @param
     */
    public void showCityPop() {
        binding.sct.contentSelect(false,true,1);
        popCity.showPopwindow(binding.sct, 0, 0);
    }

    private void setTextButton(){
        SelectPopEntity selectPopEntity1 = new SelectPopEntity("团队规模", "1", false, true);
        SelectPopEntity selectPopEntity2 = new SelectPopEntity("地区", "2", false, true);
        binding.sct.addTextButton(selectPopEntity1);
        binding.sct.addTextButton(selectPopEntity2);
    }
}
